package com.hzvtc.myproject.interceptor;

import com.hzvtc.myproject.config.Constant;
import com.hzvtc.myproject.exception.HttpException;
import com.hzvtc.myproject.utils.HttpCode;
import com.hzvtc.myproject.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final RedisUtil redisUtil;

    /**
     * 构造一个登录拦截器对象
     *
     * @param redisUtil Redis工具类
     */
    public LoginInterceptor(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 在请求处理之前进行拦截验证用户是否登录
     *
     * @param request  HttpServletRequest对象
     * @param response HttpServletResponse对象
     * @param handler  被拦截的处理器对象
     * @return 是否继续处理该请求
     * @throws Exception 如果发生异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constant.HEADER_TOKEN);
        if (token == null) {
            throw new HttpException(HttpCode.NOT_LOGIN, "未登录");
        } else {
            if (!redisUtil.hasToken(token)) {
                throw new HttpException(HttpCode.LOGIN_EXPIRED, "登录已过期");
            } else {
                redisUtil.exchange(token).orElseThrow(() -> new HttpException(HttpCode.LOGIN_EXPIRED, "登录用户不存在"));
                redisUtil.setExpireTime(token);
                return true;
            }
        }
    }
}
